package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxApiController
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-10-17 19:54
 * @Version 1.0
 */
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {

    @Autowired
    private UserInfoService userInfoService;

    //获取微信登录参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getLoginParam() throws UnsupportedEncodingException {
        Map<String,Object> map = new HashMap<>();
        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
        map.put("appid",ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri",redirectUri);//微信扫码后，在微信端点击确认后的重定向接口，并携带code
        map.put("scope","snsapi_login");
        map.put("state",System.currentTimeMillis()+"");
        return R.ok().data(map);
    }

    @GetMapping("callback")
    public String callback(String code){
        //1、微信端确认后，回调该接口，获取临时票据 code
        System.out.println("code = " + code);

        try {
            //2. 根据临时票据code获取access_token 和 openid
            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + ConstantPropertiesUtil.WX_OPEN_APP_ID + "" + "&secret=" + ConstantPropertiesUtil.WX_OPEN_APP_SECRET + "" + "&code=" + code + "&grant_type=authorization_code";
            String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);
            JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);

            //得到 openid 和 access_token
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //3. 根据openid 从 mysql中查询用户
            UserInfo userInfo = userInfoService.selectWxInfoByOpenId(openid);
            if (userInfo == null) {
                //4. 根据 access_token 和 openid 获取微信用户昵称
                String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                String nickname = resultUserInfoJson.getString("nickname");

                //5. 添加该微信用户
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);

                userInfoService.save(userInfo);
            }

            //-------------------------------------
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)){
                name = userInfo.getNickName();
                if (StringUtils.isEmpty(name)){
                    name = userInfo.getPhone();
                }
            }

            String token = JwtHelper.createToken(userInfo.getId(), name);
            //跳转到前端页面 pages/weixin/callback.vue
            //手机号为空：传递openid     手机号不为空：不传openid ；  前端根据openid是否为空决定接下来是否需要绑定手机号
            return "redirect:http://localhost:3000/weixin/callback?" +
                    "name="+URLEncoder.encode(name,"utf-8")  +"&" +
                    "token="+token + "&" +
                    "openid="+  (StringUtils.isEmpty(userInfo.getPhone())==true?userInfo.getOpenid():"");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
